package morenoapp.components.config2;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import morenoapp.MorenoApp;
import morenoapp.components.common.VerticalLayout;
import morenoapp.model.data.MorenoQuestionFace;
import morenoapp.model.listeners.MorenoModelAdapter;
import morenoapp.util.DocumentedComponent;
import morenoapp.util.I18N;
import morenoapp.util.MorenoUtil;
import org.jdesktop.application.Action;

/**
 * Редактор списка вопросов.
 * 
 * @author dmitry.mamonov
 */
@DocumentedComponent
public class QuestionsListEditorJPanel extends JPanel {
    Map<MorenoQuestionFace, QuestionEditorJPanel> questionsListMap = new LinkedHashMap<MorenoQuestionFace, QuestionEditorJPanel>();
    public QuestionsListEditorJPanel() {
        initComponents();
        intiLayout();
    }

    private void intiLayout() {
        //setLayout(new VerticalLayout(0, VerticalLayout.BOTH));
        BoxLayout layooutBox = new BoxLayout(this, BoxLayout.PAGE_AXIS);
        setLayout(layooutBox);
        addStrutIfEmpty();
        setBackground(Color.GRAY);
    }

    private void initComponents() {
        MorenoApp.getModel().addModelListener(new MorenoModelAdapter() {
            @Override
            public void onQuestionsListChanged() {
                actionUpdateQuestionsList();
            }

        });
    }

    private void addStrutIfEmpty() {
        if (getComponentCount() == 0) {
            add(Box.createVerticalStrut(80));
        }
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        if (questionsListMap.isEmpty()==true) {
            MorenoUtil.drawStringAtComponentCenter(g, this, Color.WHITE, null, I18N.get("question_list_editor.no_questions"));
        }
    }

    @Action
    public void actionUpdateQuestionsList() {
        this.removeAll();
        Map<MorenoQuestionFace, QuestionEditorJPanel> newQuestionsListMap = new LinkedHashMap<MorenoQuestionFace, QuestionEditorJPanel>();
        for (MorenoQuestionFace question : MorenoApp.getModel().getQuestionsList()) {
            QuestionEditorJPanel editor = newQuestionsListMap.get(question);
            if (editor == null) {
                editor = new QuestionEditorJPanel(question);
            }
            newQuestionsListMap.put(question, editor);
        }
        questionsListMap = newQuestionsListMap;

        //TODO add animation if so
        for (QuestionEditorJPanel editor : questionsListMap.values()) {
            add(editor);
        }
        addStrutIfEmpty();

        this.revalidate();
        this.repaint();
    }

}
